<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkAgent\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Logger\LoggerFactory;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Corp\Utils\WeWorkFactory;
use MoChat\App\WorkAgent\Contract\WorkAgentContract;
use MoChat\App\WorkDepartment\Queue\SyncDepartmentQueue;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use Psr\Log\LoggerInterface;

/**
 * 企业应用 - 获取发布状态
 *
 * Class PublishStatus.
 * @Controller
 */
class PublishStatus extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SyncDepartmentQueue
     */
    protected $syncDepartmentQueue;

    /**
     * @Inject
     * @var WorkAgentContract
     */
    private $workAgentService;

    /**
     * @Inject
     * @var CorpContract
     */
    private $corpService;

    /**
     * @Inject
     * @var WeWorkFactory
     */
    private $weWorkFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/agent/publishStatus", methods="get")
     */
    public function handle(): array
    {
        $loggerFactory = $this->container->get(LoggerFactory::class);
        $this->logger = $loggerFactory->get(__CLASS__);

        $user = user();
        $corpId = (int) $user['corpIds'][0];

        $agent = $this->workAgentService->getWorkAgentCustomizedAppByCorpId($corpId);

        if (empty($agent)) {
            return [
                'agentId' => 0,
                'publishStatus' => 0,
            ];
        }

        $publishStatus = [
            'agentId' => $agent['id'],
            'publishStatus' => 1,
        ];

        $agentApp = $this->weWorkFactory->getAgentApp((int) $agent['id']);
        $wxResult = $agentApp->agent->get((int) $agent['wxAgentId']);

        if ($wxResult['errcode'] !== 0) {
            $this->logger->warning(sprintf('获取应用信息出错，错误：%s', $wxResult['errmsg']));
            return $publishStatus;
        }

        if ($wxResult['customized_publish_status'] != 2) {
            return $publishStatus;
        }

        $this->workAgentService->updateWorkAgentById((int) $agent['id'], ['customized_publish_status' => 2]);

        // 代开发应用授权成功，开始同步通讯录
        $this->syncDepartmentQueue->syncDepartmentByCorpId(['corpId' => $corpId]);

        return [
            'agentId' => $agent['id'],
            'publishStatus' => 2,
        ];
    }
}
